import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

# from langchain_openai import ChatOpenAI
# llm = ChatOpenAI(temperature=0)
from langchain_community.chat_models import ChatZhipuAI
llm = ChatZhipuAI(temperature=0, model="glm-4-plus")

from langchain_community.tools.tavily_search import TavilySearchResults
search = TavilySearchResults()
#from langchain_community.tools.searchapi.tool import SearchAPIResults
#search = SearchAPIResults()

from langchain_core.tools import Tool
from tools.amap import get_wx
from tools.excel import query_adcode
from tools.commutils import get_current_date
# tools = [query_adcode, get_wx, get_current_date, search]

tools = [
    Tool(
        name="QueryAdcode",
        func=query_adcode.invoke,
        description="检索参数指定城市或地区的adcode，参数只能是被查询城市或地区的中文名称。"
    ),
    Tool(
        name="QueryWeather",
        func=get_wx.invoke,
        description="获取参数指定城市或地区的天气，参数只能是指定城市或地区的adcode。"
    ),
    # Tool(
    #     name="GetCurrentDate",
    #     func=get_current_date.invoke,
    #     description="获取当前日期，即今天日期，不需要参数。"
    # ),
    Tool(
        name="Search",
        func=search.invoke,
        description="用于网络搜索景点信息，请使用中文关键字进行搜索。"
    ),
]

from langchain_experimental.plan_and_execute import (
    PlanAndExecute, 
    load_agent_executor, 
    load_chat_planner
)

planner = load_chat_planner(llm)
executor = load_agent_executor(
    llm, 
    tools, 
    verbose=True, 
    include_task_in_prompt=True
    )
agent = PlanAndExecute(
    planner=planner, 
    executor=executor, 
    verbose=True, 
    handle_parsing_errors=True
    )

#from langchain.prompts import PromptTemplate
from langchain_core.prompts import PromptTemplate
with open("prompt.txt", 'r', encoding='utf-8') as f:
    prompt = PromptTemplate.from_template(f.read())

startDate = "明天"
during = 3
destination = "天津"
ta = "历史人文"
prompt = prompt.format(
    tools = tools,
    startDate=startDate, 
    during=during, 
    destination=destination, 
    ta=ta
    )

result = agent.invoke(prompt, handle_parsing_errors=True)
print(f"\n====最终结果====\n{result['output']}")